from django.http import HttpResponse
from django.contrib.auth.decorators import login_required
from iperscribo.thirdparty.decorators import json_view
from iperscribo.thirdparty.djangologging import debug, info, error, warn
from iperscribo.messages.models import Message
from django.contrib.contenttypes.models import ContentType
import datetime, time
#################################################################################################################################################

@login_required
@json_view
def save(request, project_uid, message_uid):
    
    document_type = request.POST['document_type']
    document_uid = request.POST['document_uid']
    text = request.POST['text']
    date = request.POST['date']
    message_type = int(request.POST['message_type'])
    debug('current_date: %s' % date)
    current_date = datetime.datetime( *time.strptime(date, '%d-%m-%Y %H:%M %p')[:6] )
    
#    print 'document_type: ', document_type
#    print 'document_uid: ', document_uid
#    print 'text: ', text
#    print 'date: ', date
#    print 'currentdate: ', current_date
#    print 'message_uid', message_uid
    
    #Check if current message already exists.
    try:
        current_message = Message.objects.get(uid = message_uid)
        current_message.text = text
        current_message.date = current_date
        current_message.save()
    except:
        
        #print 'in exception'
        current_document_type = ContentType.objects.get(name=document_type)
        #print 'document'
        current_document = current_document_type.get_object_for_this_type(uid=document_uid)
        #print 'before current message'
        current_message = Message(uid=message_uid, document_type=current_document_type, document_uid=document_uid, owner=request.user, text=text, type=message_type)
        #print 'before save'
        current_message.save()
        
    
    
#    current_document_type = ContentType.objects.get(document_type)
#    current_document = current_document_type.get_object_for_this_type(uid=document_uid)
#    current_message = Message(uid=message_uid, document_type=current_document_type, document_uid=document_uid, owner=request.user, text=text)
#    current_message.save()
    
    #print 'before return'
    return {'message' : 'DONE'}

#################################################################################################################################################

@login_required
@json_view
def remove(request, project_uid, message_uid):
    
    try:
        Message.objects.get(uid = message_uid).delete()
        return {'message' : 'DONE'}
    except Exception, ex:
        return {'message' : 'ERROR'}
    

